import 'dart:async';
import 'package:get/get.dart';
import 'package:hc_bot_pro/common/speech/asr.dart';
import 'package:hc_bot_pro/common/speech/tts.dart';
import 'package:hc_voice_plugin/hc_voice_plugin.dart'
    show HcVoicePlugin, TtsMode;

import 'package:flutter/foundation.dart';
// import 'package:hc_voice_plugin/online_tts.dart';
// import 'package:hc_voice_plugin/online_voice_manager.dart';

class HCAISpeechService {
  final HCBotASR asr = HCBotASR();
  final HCBotTTS tts = HCBotTTS();

  Timer? _timer;

  Future setUp() async {
    // 使用在线TTS模式（阿里云语音服务）
    await HcVoicePlugin().init(
      // ttsMode: TtsMode.online,
      // onlineConfig: OnlineConfig(appKey: "yopZM0Rr2IgPN2FD"),
    );

    HcVoicePlugin().awake.listen((event) {
      if (asr.onAwake != null) {
        asr.onAwake!();
      }
      resetTimer();
    });

    HcVoicePlugin().speechRecognizedCompleted.listen((event) {
      if (asr.onASRCompleted != null) {
        asr.onASRCompleted!(event);
      }
    });

    HcVoicePlugin().speakCompleted.listen((event) {
      resetTimer();
      if (tts.onSayingCompleted != null) {
        tts.onSayingCompleted!();
      }
    });
  }

  Future stop() async {
    cancelTimer();
    await HcVoicePlugin().stop(isTtsStop: false);
  }

  Future<void> start() async {
    resetTimer();
    await HcVoicePlugin().start();
  }

  void dispose() {
    HcVoicePlugin().dispose();
  }
}

extension on HCAISpeechService {
  void cancelTimer() {
    debugPrint("HCAIBot cancelTimer");

    _timer?.cancel();
    _timer = null;
  }

  void resetTimer() {
    debugPrint("HCAIBot startTimer");
    cancelTimer();
    _timer = Timer(20.minutes, () {
      asr.sleep();
    });
  }
}
